import React, { useState, useEffect, useRef } from 'react'
import {
	Table,
	Button,
	Modal,
	Tree,
	message
} from 'antd'
import {
	DeleteOutlined,
	UnorderedListOutlined,
	ExclamationCircleOutlined
} from '@ant-design/icons'
import { deleteRoleById, deleteRoleRightByRoleId } from '../../../utils/request/delete'
import { getRoles, getRights, getAllRight, getRightsOfNewRole } from '../../../utils/request/get'
import { updateRightByRoleId } from '../../../utils/request/put'
import { useSelector } from 'react-redux'
import { addRole, addRoleWithRight } from '../../../utils/request/post'
import RoleForm from '../../../components/rightManage/roleForm'

const { confirm } = Modal

export default function RoleList() {
	const [dataSource, setDataSource] = useState([])
	const [treeData, setTreeData] = useState([])
	const [currentRights, setCurrentRights] = useState([])
	const [currentId, setCurrentId] = useState(0)
	const [isModalVisible, setIsModalVisible] = useState(false)
	const [isAddVisible, setIsAddVisible] = useState(false)
	const token = useSelector(state => state.TokenReducer.token)
	const addForm = useRef(null)

	useEffect(() => {
		async function fetchData() {
			const res = await getRoles()
			setDataSource(res)
		}
		fetchData()
	}, [])

	useEffect(() => {
		async function fetchData() {
			if (token) {
				const res = await getRights(token.roleId)
				let data = []
				res.forEach(item => {
					if (item.grade === 1) {
						data.push(item)
					}
				})
				setTreeData(data)
			}
		}
		fetchData()
	}, [token])

	const deleteData = (item) => {
		setDataSource(dataSource.filter(data => data.id !== item.id));
		deleteRoleById(item.id)
		deleteRoleRightByRoleId(item.id)
	}

	const showConfirm = (type, item) => {
		let obj = {
			icon: <ExclamationCircleOutlined />,
		}
		switch (type) {
			case 'CANCEL':
				obj.title = '您确定要取消吗?'
				obj.onOk = function () { }
				obj.onCancel = function () { console.log('Cancel'); }
				break
			case 'DELETE':
				obj.title = '您确定要删除吗?'
				obj.cancelText = '取消'
				obj.okText = '确定'
				obj.onOk = function () { deleteData(item); }
				obj.onCancel = function () { console.log('Cancel'); }
				break
			default: break
		}
		confirm(obj)
	};

	const openModal = (item) => {
		// console.log(item);
		setIsModalVisible(true)
		setCurrentRights(item.rights)
		setCurrentId(item.id)
	}

	const columns = [
		{
			title: 'ID',
			dataIndex: 'id',
			render: (id) => {
				return <b>{id}</b>
			}
		},
		{
			title: '角色名称',
			dataIndex: 'roleName',
		},
		{
			title: '操作',
			render: (record) => {
				return (
					<div>
						<Button
							danger onClick={() => showConfirm("DELETE", record)}
							shape="circle" icon={<DeleteOutlined />}>
						</Button>&nbsp;&nbsp;
						<Button
							shape="circle"
							icon={<UnorderedListOutlined />}
							type="primary"
							onClick={() => { openModal(record) }}></Button>
					</div>
				)
			},
		}
	]

	const handleOk = async () => {
		setIsModalVisible(false)
		// console.log(currentRights);
		const rights = await patchRights()

		updateRightByRoleId(currentId, rights).then(res => {
			const data = res.data.Role
			if (data.msg) {
				message.error(data.msg)
				return
			}
			setDataSource(dataSource.map(item => {
				if (item.id === currentId) {
					return { ...item, rights: currentRights }
				}
				return item
			}))
		})
		message.success('修改成功')
	}

	const addFormMethod = () => {
		addForm.current.validateFields().then(value => {
			setIsAddVisible(false)
			addForm.current.resetFields()
			addRole(value).then(async res => {
				const data = res.data.role
				const rightId = value.right
				const { allRightId, keys } = await getRightsOfNewRole(rightId)
				// console.log(allRightId, keys);
				const addRes = await addRoleWithRight(data.id, allRightId)
				if (!addRes) {
					message.success('添加失败')
					return
				}
				setDataSource([...dataSource, { ...data, rights: keys }])
				message.success('添加成功')
				// console.log(newRole);
			})

		}).catch(err => { showError(err) })
	}

	const showError = (err) => {
		const errors = err.errorFields
		if (errors.length > 0) {
			message.warning(errors[0].errors[0])
		}
	}

	const patchRights = async () => {
		const res = await getAllRight()
		let rights = []
		const data = res.data.rights
		for (let i = 0; i < currentRights.length; i++) {
			const item = currentRights[i]
			for (let j = 0; j < data.length; j++) {
				const element = data[j]
				if (element.key === item) {
					rights.push({ rightId: element.id })
				}
			}
		}
		return rights
	}

	const handleCancel = () => {
		setIsModalVisible(false)
	}

	const onCheck = (checkedKeysValue) => {
		// console.log(checkedKeysValue);
		setCurrentRights(checkedKeysValue);
	};

	return (
		<>
			<Button
				type="primary"
				style={{ marginBottom: '5px' }} onClick={() => setIsAddVisible(true)}>添加角色</Button>
			<Table
				bordered
				columns={columns}
				dataSource={dataSource}
				pagination={{ pageSize: 5 }}
				rowKey={(item) => item.id}
			/>
			<Modal
				title="权限控制"
				cancelText="取消"
				okText="确定"
				open={isModalVisible}
				onOk={handleOk}
				onCancel={handleCancel}>
				<Tree
					checkable
					onCheck={onCheck}
					checkedKeys={currentRights}
					treeData={treeData}
				/>
			</Modal>
			<Modal
				className='modal'
				open={isAddVisible}
				title="添加角色"
				okText="完成"
				cancelText="取消"
				onCancel={() => setIsAddVisible(false)}
				onOk={() => addFormMethod()}
			>
				<RoleForm ref={addForm}></RoleForm>
			</Modal>
		</>
	)
}